package com.example.mylogin.controller;

import com.example.mylogin.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;

@Controller
@RequestMapping("login")
public class LoginController {

    @RequestMapping("toLogin")
    public String toLogin() {
        System.out.println("================++++++++++++++跳转登录页面");
        return "login";
    }

    @RequestMapping("loginSystem")
    public String loginSystem(String username, String password, HttpSession session) throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        User user = new User();
        user.setUsername(username);
        User result = sqlSession.selectOne("userMapper.selectOne", user);
        //释放资源
        sqlSession.close();
        // 合法用户，信息写入session，同时跳转到系统主页面
        boolean equals = result == null ? false : password.equals(result.getPassword());
        if (equals) {
            System.out.println("合法用户");
            session.setAttribute("username", username + System.currentTimeMillis());
            return "redirect:/login/success";
        } else {
            // 非法用户返回登录页面
            System.out.println("非法，跳转");
            return "redirect:/login/fail";
        }
    }

    @RequestMapping("/success")
    public String success() {
        return "success";
    }

    @RequestMapping("/fail")
    public String fail() {
        return "fail";
    }
}
